require 'rbconfig'
dl_ext = RbConfig::CONFIG['DLEXT']

namespace :rbx_parser do

  _ = lambda { |file| File.expand_path(file, File.dirname(__FILE__)); }

  lexer_c = file _["lexer.c"] => _["lexer.lex"] do |task|
    Dir.chdir _["."] do
      say "Generating lexer source for Rubinius"
      sh 'flex', '--outfile', task.to_s, '--header-file=lexer.h', task.prerequisites.first
    end
  end

  parser_c = file _["parser.c"] => _["parser.y"] do |task|
    Dir.chdir(_["."]) do
      say "Generating parser source for Rubinius"
      sh "bison", "--output", task.to_s, "-d", "-v", task.prerequisites.first
    end
  end

  makefile = file _["Makefile"] => [_["extconf.rb"], lexer_c, parser_c] do |task|
    Dir.chdir(_["."]) { sh 'rbx', task.prerequisites.first }
  end

  desc "Builds the parser."
  task :parser => parser_c

  desc "Builds the lexer."
  task :lexer => lexer_c

  desc "Compiles the generated lexer and parser."
  task :compile => [makefile, parser_c, lexer_c] do
    say "Building parser bundle for Rubinius"
    sh! 'make', '-C', _["."]
  end

  parser_e = _["fancy_parser.#{dl_ext}"]
  parser_e_task = file parser_e => :compile
  # task :ext => parser_e
  task :ext do
    unless File.exist? parser_e
      parser_e_task.invoke
    end
  end

  desc "Cleans up generated files."
  task :clean do
    say "Cleaning Rubinius parser in #{_["."]}"
    sh 'make', '-C', _["."], "clean" rescue nil
    rm_f lexer_c.to_s,       :verbose => false
    rm_f parser_c.to_s,      :verbose => false
    rm_f parser_e.to_s,      :verbose => false
    rm_f makefile.to_s,      :verbose => false
    rm_f _["lexer.h"],       :verbose => false
    rm_f _["parser.h"],      :verbose => false
    rm_f _["parser.output"], :verbose => false
    rm_f Dir.glob(_["*.{o,so,rbc,log}"]), :verbose => false
  end

  desc "Invokes the compile task."
  task :default => :compile
end


task :clean_parser => :"rbx_parser:clean"
